package com.dk.file.service.impl;

import com.dk.file.dto.QiniuOSSDto;
import com.dk.file.service.QiniuYunService;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
@Slf4j
public class QiniuYunServiceImpl implements QiniuYunService {

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private QiniuOSSDto qiniuOSSDto;

    @Override
    public String upload(String fileName, InputStream ips, String mimeType) {
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        //3.生成上传需要的token
        Auth auth = Auth.create(qiniuOSSDto.getAk(), qiniuOSSDto.getSk());
        String upToken = auth.uploadToken(qiniuOSSDto.getBucket());
        try {
            //4.文件的上传,需要5个参数
            Response response = uploadManager.put(ips, key, upToken,null,mimeType);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            //最终图片地址
            String path = qiniuOSSDto.getBaseUrl()+putRet.key;
            return path;
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
